<template>
    <div class="content">
        <div class="top">
            <ul>
                <li>
                    <SelectIpt>
                        <p>发布状态</p>
                    </SelectIpt>
                </li>
                <li>
                    <TextIpt>
                        <p>公告标题</p>
                    </TextIpt>
                </li>
            </ul>
            <div class="bth">
                <BlueBtn>查询</BlueBtn>
                <BlueBtn @click.native="addData">新增</BlueBtn>
            </div>
        </div>
        <div class="table">
            <el-table :data="filterData.slice(pages, pages + 10)" border style="width: 100%">
                <el-table-column prop="Content" label="标题内容" width="260">
                </el-table-column>
                <el-table-column prop="CreateDate" label="创建时间" width="260">
                </el-table-column>
                <el-table-column prop="CreateMan" label="创建人" width="220">
                </el-table-column>
                <el-table-column prop="ShowTime" label="展示时间" width="280">
                </el-table-column>
                <el-table-column prop="ShowState" label="发布状态" width="250">
                </el-table-column>
                <el-table-column label="操作">
                    <template slot-scope="scope">
                        <el-button size="mini" @click="lookIntro(scope.row, 1)">详情</el-button>
                        <el-button size="mini" @click="lookIntro(scope.row, 0, scope.$index)">编辑</el-button>
                        <el-button size="mini" type="danger"
                            @click="handleDelete(scope.$index, scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="page">
                <div class="total-page">
                    <p>共<span>{{ Math.ceil(filterData.length / 10) }}</span>页/<span>{{ filterData.length }}</span>条数据
                    </p>
                </div>
                <el-pagination background layout="prev, pager, next,jumper" @current-change="getPage" :page-size=10
                    :current-page.sync=page :total="filterData.length" hide-on-single-page>
                </el-pagination>
            </div>
        </div>
        <!-- 查看详情对话框 -->
        <el-dialog title="公告详情/编辑" :visible.sync="noteDialog" width="40%" class="noteDialog"
            :before-close="handleClose">
            <el-form :disabled="isEdit" ref="noteForm" :inline="true" :rules="rules" :model="noteForm"
                label-width="80px">
                <el-form-item label="发布人" prop="pageSizeublisher">
                    <el-input v-model="noteForm.pageSizeublisher"></el-input>
                </el-form-item>
                <el-form-item label="内容标题" prop="contentTitle">
                    <el-input v-model="noteForm.contentTitle"></el-input>
                </el-form-item>
                <el-form-item v-if="isEdit" label="创建时间" prop="createTime">
                    <el-input v-model="noteForm.createTime"></el-input>
                </el-form-item>

                <el-form-item label="公告类型" prop="noteType">
                    <el-select v-model="noteForm.noteType" placeholder="请选择公告类型">
                        <el-option value="物业公告"></el-option>
                        <el-option value="节假日通知"></el-option>
                        <el-option value="安全通知"></el-option>
                        <el-option value="设备维护"></el-option>
                        <el-option value="交通通知"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="发布状态" prop="noteState">
                    <el-select v-model="noteForm.noteState" placeholder="请选择发布状态">
                        <el-option value="已发布"></el-option>
                        <el-option value="未发布"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="通知方式" prop="notification">
                    <el-select v-model="noteForm.notification" placeholder="请选择通知方式">
                        <el-option value="短信通知"></el-option>
                        <el-option value="微信公众号通知"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="接收人" prop="recipient">
                    <el-select v-model="noteForm.recipient" placeholder="请选择接收人">
                        <el-option value="小区住户"></el-option>
                        <el-option value="物业人员"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="展示时间" prop="showTime">
                    <!-- <el-input v-model="noteForm.showTime"></el-input> -->
                    <el-date-picker v-model="noteForm.showTime" type="datetime" placeholder="选择日期时间">
                    </el-date-picker>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer" v-show="!isEdit">
                <el-button @click="handleClose">取 消</el-button>
                <el-button type="primary" @click=" submitNote('noteForm')">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import BlueBtn from '@/components/BlueBtn.vue';
import SelectIpt from '@/components/SelectIpt.vue';
import TextIpt from '@/components/TextIpt.vue';
export default {
    components: {
        BlueBtn,
        SelectIpt,
        TextIpt
    },
    data() {
        return {
            isAdd: false,
            pages: 0,
            page: 0,
            isEdit: true,
            allData: [],
            filterData: [],
            noteDialog: false,
            noteForm: {
                pageSizeublisher: '',
                contentTitle: "",
                createTime: '',
                showTime: '',
                noteType: '',
                noteState: '',
                notification: "",
                recipient: '',
                index: "",
                id: '',
            },
            rules: {
                pageSizeublisher: [
                    { required: true, message: '请输入发布人姓名', trigger: 'blur' },
                ],
                contentTitle: [
                    { required: true, message: '请输入内容标题', trigger: 'blur' },
                ],
                showTime: [
                    { required: true, message: '请输入展出时间', trigger: 'blur' },
                ],
                noteType: [
                    { required: true, message: '请选择公共类型', trigger: 'blur' },
                ],
                noteState: [
                    { required: true, message: '请选择公共状态', trigger: 'blur' },
                ],
                notification: [
                    { required: true, message: '请选择通知方式', trigger: 'blur' },
                ],
                recipient: [
                    { required: true, message: '请选择接收人', trigger: 'blur' },
                ]
            }


        }
    },
    methods: {
        insertNote() {
            this.$axios.post('http://127.0.0.1/active/insertAnnouncement', {
                ...this.noteForm
            }, {
                headers: {
                    'Authorization': `Bearer ${localStorage.getItem('token')}`,
                    'Content-Type': 'application/json' // 如果需要发送 JSON 数据，则包含此行 // 设置请求头
                }
            }).then(res => {
                this.noteDialog = false
                this.$message({
                    type: 'success',
                    message: '修改成功!'
                });
            }).catch(err => {
                console.log(err);
            })
        },
        addData() {
            this.noteForm.pageSizeublisher = ''
            this.noteForm.contentTitle = ''
            this.noteForm.createTime = ''
            this.noteForm.showTime = ''
            this.noteForm.noteType = ''
            this.noteForm.noteState = ''
            this.noteForm.notification = ''
            this.noteForm.recipient = ''
            this.isAdd = true
            this.noteDialog = true
            this.isEdit = false
        },
        updateNote() {
            this.$axios.post('http://127.0.0.1/active/updateAnnouncement', {
                ...this.noteForm
            }, {
                headers: {
                    'Authorization': `Bearer ${localStorage.getItem('token')}`,
                    'Content-Type': 'application/json' // 如果需要发送 JSON 数据，则包含此行 // 设置请求头
                }
            }).then(res => {
                this.noteDialog = false
                this.$message({
                    type: 'success',
                    message: '修改成功!'
                });
            }).catch(err => {
                console.log(err);
            })
        },
        formatDate(dateStr) {
            // 创建 Date 对象
            const date = new Date(dateStr);

            // 获取年、月、日、小时、分钟（使用本地时区）
            const year = date.getFullYear(); // 本地时间的年份
            const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始，所以需要加1
            const day = String(date.getDate()).padStart(2, '0');
            const hour = String(date.getHours()).padStart(2, '0');
            const minute = String(date.getMinutes()).padStart(2, '0');

            // 格式化为 "YYYY-MM-DD HH:MM"
            return `${year}-${month}-${day} ${hour}:${minute}`;
        },
        submitNote(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    this.noteForm.showTime = this.formatDate(this.noteForm.showTime)
                    if (this.isAdd) {
                        this.insertNote()
                    } else {
                        let flag = false
                        if (this.filterData[this.noteForm.index].Content != this.noteForm.contentTitle) {
                            this.filterData[this.noteForm.index].Content = this.noteForm.contentTitle
                            flag = true
                        }
                        if (this.filterData[this.noteForm.index].CreateMan != this.noteForm.pageSizeublisher) {
                            this.filterData[this.noteForm.index].CreateMan = this.noteForm.pageSizeublisher
                            flag = true
                        }
                        if (this.filterData[this.noteForm.index].ShowTime != this.noteForm.showTime) {
                            this.filterData[this.noteForm.index].ShowTime = this.noteForm.showTime
                            flag = true
                        }
                        if (this.filterData[this.noteForm.index].ShowState != this.noteForm.noteState) {
                            this.filterData[this.noteForm.index].ShowState = this.formatDate(this.noteForm.noteState)
                            flag = true
                        }
                        if (this.filterData[this.noteForm.index].InformType != this.noteForm.notification) {
                            this.filterData[this.noteForm.index].InformType = this.formatDate(this.noteForm.notification)
                            flag = true
                        }
                        if (this.filterData[this.noteForm.index].Recipient != this.noteForm.recipient) {
                            this.filterData[this.noteForm.index].Recipient = this.formatDate(this.noteForm.recipient)
                            flag = true
                        }
                        if (this.filterData[this.noteForm.index].AnnouncementType != this.noteForm.noteType) {
                            this.filterData[this.noteForm.index].AnnouncementType = this.formatDate(this.noteForm.noteType)
                            flag = true
                        }
                        if (flag) {
                            this.updateNote()
                        } else {
                            this.noteDialog = false
                        }
                    }

                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },
        handleClose() {
            this.$confirm('确认关闭？')
                .then(_ => {
                    this.noteDialog = false
                })
                .catch(_ => { });
        },
        lookIntro(row, index, indexs) {
            this.isAdd = false
            if (index) {
                this.isEdit = true
            } else {
                this.isEdit = false
                this.noteForm.index = indexs + this.pages
                this.noteForm.id = row.ID
            }
            this.noteForm.pageSizeublisher = row.CreateMan
            this.noteForm.contentTitle = row.Content
            this.noteForm.createTime = row.CreateDate
            this.noteForm.showTime = row.ShowTime
            this.noteForm.noteType = row.AnnouncementType
            this.noteForm.noteState = row.ShowState
            this.noteForm.notification = row.InformType
            this.noteForm.recipient = row.Recipient

            this.noteDialog = true
        },
        getAllData() {
            this.$axios.get('http://127.0.0.1/active/announcement', {
                headers: {
                    'Authorization': `Bearer ${localStorage.getItem('token')}`,
                    'Content-Type': 'application/json' // 如果需要发送 JSON 数据，则包含此行 // 设置请求头
                }
            }).then(res => {
                this.allData = res.data
                this.filterData = res.data
            }).catch(err => {
                console.log(err);
            })
        },
        //get 当前页
        getPage(page) {
            this.pages = 10 * (page - 1)
        },
    },
    mounted() {
        this.getAllData()
    }
}
</script>

<style scoped>
.noteDialog>>>.el-dialog__body {
    padding: 30px 50px;
}

.noteDialog>>>.el-input {
    width: 217px;
}

.table>>>.el-table {
    min-height: 580px;
}

.page {
    display: flex;
    align-items: center;
    justify-content: end;
    margin-top: 20px;
}

.page>>>button {
    min-width: 35px !important;
    height: 25px;
    line-height: 25px;
    border-radius: 3px !important;
    border: 1px solid rgba(215, 215, 215, 1);
    background: #fff !important;
}

.page>>>.active {
    border-color: rgba(26, 135, 254, 1) !important;
    background-color: rgba(26, 135, 254, 1) !important;
    color: #fff !important;
}

.page>>>.el-pager li {
    min-width: 35px !important;
    height: 25px;
    line-height: 25px;
    border-radius: 3px !important;
    border: 1px solid rgba(215, 215, 215, 1);
    font-size: 12px;
    color: #999;
    font-weight: normal !important;
    background: #fff;
}

.total-page span {
    color: #FF3C2C;
}

.total-page {
    font-size: 12px;
    color: #666;
}

.top ul {
    white-space: nowrap;
    font-size: 13px;
    color: #666;
    display: flex;
}

.top li {
    margin-right: 50px;
    margin-bottom: 20px;
}

.top {
    background: #fff;
    padding: 20px 35px;
    border-radius: 4px;
}
</style>